package com.decent.text.pdf.test2;


import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.lang3.RandomStringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.time.LocalDateTime;

/**
 * @author 王雪杰
 * @date 2021/11/12 17:49
 */
public class CreatePDFByHtml {

    public static void main(String[] args) throws IOException {
        String pdfPath = "D:\\idea\\workspace\\test-4-7\\src\\main\\resources\\pdfTest\\z" + LocalDateTime.now().getMinute() +RandomStringUtils.randomAlphanumeric(3) + ".pdf";
        String htmlFilePath = "D:\\idea\\workspace\\test-4-7\\src\\main\\resources\\pdfTest\\测试pdf.html";
        createPDFByHtml(pdfPath, htmlFilePath);
    }

    /**
     * 该方法用来将指定的word文件转换成pdf文件（使用flying saucer技术）
     *
     * @param pdfPath:生成后的pdf所在目录，包括目录+pdf名称+.+pdf
     * @param htmlFilePath:需要进行转换的html文件所在目录，包括目录+html名称+.+html
     */
    public static boolean createPDFByHtml(String pdfPath, String htmlFilePath) {
        boolean result = false;
        //1、判断给定的文件是否是html文件:是htm格式结尾，或者以html格式结尾
        if (htmlFilePath.toUpperCase().endsWith(".HTM") ||
                htmlFilePath.toUpperCase().endsWith(".HTML")) {//两种格式都是扫描文件格式
            try {
                OutputStream os = new FileOutputStream(pdfPath);
                ITextRenderer renderer = new ITextRenderer();
                String str = CreateHtmlByFreemarker.getHtmlStr();
                System.out.println(str);
                System.out.println("--------------=============");
                Document doc = Jsoup.parse(str);

                System.out.println(doc.html());
                Elements elements = doc.select("img");
                int i = 0;
                for (Element element : elements) {
                    element.attr("id", i + "");
                    i++;
                }


                String content = doc.html();
                content = content.replace("&nbsp;", "&#160;");
                // content = content.replace("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">", "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></meta>");
                content = content.replace("(filtered)\">", "(filtered)\"></meta>");
                content = content.replaceAll("<br>", "<br></br>");
                for (Element element : elements) {
                    String startStr = element.outerHtml();
                    String endStr = element.outerHtml() + "</img>";
                    content = content.replace(startStr, endStr);
                }


                ITextFontResolver fontResolver = renderer.getFontResolver();

                // fontResolver.addFont("/Users/liqi/ideaWorkspace/java-export-word-plugin-master/PluginExample/src/main/resources/ftl/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //fontResolver.addFont("/Users/liqi/ideaWorkspace/java-export-word-plugin-master/PluginExample/src/main/resources/ftl/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);



               // mac
               //  fontResolver.addFont("/library/fonts/Arial Unicode.ttf",
               //          BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                // linux：
                // fontResolver.addFont("/usr/share/fonts/TTF/ARIALUNI.TTF",
                //         BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                // windows:
                fontResolver.addFont("C:/Windows/Fonts/Arial.TTF",
                        BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


                // 解决中文支持问题
                // fontResolver.addFont("/library/fonts/Arial Unicode.ttf",
                //         BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                renderer.setDocumentFromString(content);

                renderer.layout();
                renderer.createPDF(os);
                os.close();
                result = true;
            } catch (Exception e) {
                result = false;
                e.printStackTrace();
            }
        } else {
            result = false;
        }
        return result;
    }
}